package com.lsf.modules.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lsf.common.api.vo.Result;
import com.lsf.modules.system.entity.Follow;
import com.lsf.modules.system.service.FollowService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author Alexander
 */
@RestController
@Slf4j
@RequestMapping("/sys/follow")
public class FollowController {

    @Resource
    private FollowService followService;

    @PostMapping("/add")
    public Result<JSONObject> add(@RequestBody @Validated Follow follow) {
        Result<JSONObject> result = new Result<>();
        LambdaQueryWrapper<Follow> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Follow::getFollowerId, follow.getFollowerId());
        queryWrapper.eq(Follow::getFollowingId, follow.getFollowingId());
        queryWrapper.groupBy(Follow::getFollowingId);
        int count = followService.count(queryWrapper);
        if (count != 0) {
            result.error500("已经关注,无法再次关注!");
            return result;
        }
        boolean save = followService.save(follow);
        if (!save) {
            result.error500("添加失败");
            return result;
        }
        result.success("添加成功");
        return result;
    }

    @PostMapping("/delete/{id}")
    public Result delete(@PathVariable String id) {
        Result result = new Result();
        Follow follow = followService.getById(id);
        if (follow == null) {
            result.error500("没有关注,无法取消!");
            return result;
        }
        boolean rm = followService.removeById(id);
        if (!rm) {
            result.error500("删除失败");
            return result;
        }
        result.success("添加成功");
        return result;
    }


}
